from urllib.parse import urlparse, parse_qs, urlencode, unquote
import json
import requests
from fastapi import APIRouter, HTTPException
from app.utils import UrlRequest, create_session

def get_headers():
    """通用请求头"""
    return {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.6533.100 Safari/537.36',
        'Referer': 'https://apitools.alipay.com/',
        'Origin': 'https://apitools.alipay.com',
        'Content-Type': 'application/json',
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'zh-CN',
        'Sec-Fetch-Site': 'same-site',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Dest': 'empty'
    }

def get_cookies(session):
    """访问 open-url 页面，获取 Cookies"""
    open_url = 'https://apitools.alipay.com/tools/open-url'
    response = session.get(open_url, headers=get_headers())
    response.raise_for_status()
    cookies = session.cookies.get_dict()
    cookies['ctoken'] = 'bigfish_ctoken_19g704h3e'
    return cookies

def parse_alipay_url(original_url):
    """解析支付宝短链接"""
    session = create_session()
    cookies = get_cookies(session)
    headers = get_headers()
    headers['Cookie'] = '; '.join([f"{key}={value}" for key, value in cookies.items()])
    post_url = 'https://apitoolsserver.alipay.com/api/solid/detect?ctoken=bigfish_ctoken_19g704h3e'
    data = {"url": original_url}
    try:
        response = session.post(post_url, headers=headers, json=data)
        response.raise_for_status()
        response_data = response.json()
        if 'data' in response_data and 'target' in response_data['data']:
            return response_data['data']['target']
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
    except json.JSONDecodeError:
        print("返回的数据格式错误，无法解析 JSON")
    return None

def convert_url_format(source_url):
    parsed_url = urlparse(source_url)
    query_params = parse_qs(parsed_url.query)
    if parsed_url.scheme == "alipays":
        return source_url
    if parsed_url.netloc == "render.alipay.com" and parsed_url.path.startswith("/p/"):
        base_url = "alipays://platformapi/startapp"
        app_id = query_params["scheme"][0].split("appId%3D")[-1].split("%26")[0]
        new_params = {}
        for key, value in query_params.items():
            if isinstance(value, list) and len(value) == 1:
                new_params[key] = unquote(value[0])
            else:
                new_params[key] = value
        new_url = f"{base_url}?appId={app_id}&" + urlencode(new_params)
        return new_url
    return source_url

zfb = APIRouter(prefix='/dpapi/v1/zfb')

@zfb.post("/")
async def api_parse_alipay(request: UrlRequest):
    converted_url = parse_alipay_url(request.url)
    if converted_url:
        converted_url = convert_url_format(converted_url)
        return {"success": True, "data": converted_url}
    raise HTTPException(status_code=400, detail="未找到转换后的链接")
